package com.bringspring.system.permission.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bringspring.common.annotation.UserPermission;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.util.DateUtil;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.RandomUtil;
import com.bringspring.common.util.UserProvider;
import com.bringspring.system.permission.constant.PermissionConst;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.entity.UserRelationEntity;
import com.bringspring.system.permission.model.user.mod.UserAllModel;
import com.bringspring.system.permission.model.userrelation.UserRelationForm;
import com.bringspring.system.permission.model.userrelation.UserRelationIdsVO;
import com.bringspring.system.permission.model.userrelation.UserRelationPagination;
import com.bringspring.system.permission.service.UserRelationService;
import com.bringspring.system.permission.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户关系
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Api(tags = "用户关系", value = "UserRelation")
@RestController
@RequestMapping("/api/permission/UserRelation")
public class UserRelationController {

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private UserService userService;

    @Autowired
    private UserProvider userProvider;

    /**
     * 列表
     *
     * @param objectId 对象主键
     * @return
     */
    @ApiOperation("获取岗位/角色/门户成员列表ids")
    @GetMapping("/{objectId}")
    public ActionResult<UserRelationIdsVO> listTree(@PathVariable("objectId") String objectId) {
        List<UserRelationEntity> data = userRelationService.getListByObjectId(objectId);
        List<String> ids = new ArrayList<>();
        for (UserRelationEntity entity : data) {
            ids.add(entity.getUserId());
        }
        UserRelationIdsVO vo = new UserRelationIdsVO();
        vo.setIds(ids);
        return ActionResult.success(vo);
    }

    /**
     * 列表
     *
     * @param objectId 对象主键
     * @return
     */
    @ApiOperation("获取岗位/角色/门户成员列表ids")
    @GetMapping("/getUserByObject/{objectId}")
    public ActionResult<List<UserAllModel>> getUserByObject(@PathVariable("objectId") String objectId) {
        List<UserRelationEntity> data = userRelationService.getListByObjectId(objectId);
        List<String> ids = new ArrayList<>();
        for (UserRelationEntity entity : data) {
            ids.add(entity.getUserId());
        }
        List<UserEntity> userList = userService.getUserName(ids);
        List<UserAllModel> voListVO = JsonUtil.getJsonToList(userList, UserAllModel.class);
        return ActionResult.success(voListVO);
    }

    /**
     * 保存
     *
     * @param userRelationForm 对象主键
     * @return
     */
    @UserPermission
    @ApiOperation("添加岗位或角色成员")
    @PostMapping("/{objectId}")
    public ActionResult save(@PathVariable("objectId") String objectId, @RequestBody UserRelationForm userRelationForm) {
        if (userRelationForm.getObjectType().equals(PermissionConst.ROLE)) {
            userRelationService.deleteAllByObjId(objectId);
            // 得到禁用的id
            userRelationService.roleSaveByUserIds(objectId, userRelationForm.getUserIds());
        } else {
            // 得到禁用的id
            List<UserRelationEntity> listByObjectId = userRelationService.getListByObjectId(objectId, PermissionConst.POSITION);
            List<String> collect = listByObjectId.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
            Set<String> set = new HashSet<>(userRelationForm.getUserIds());
//            set.addAll(userService.getUserList(collect).stream().map(UserEntity::getId).collect(Collectors.toList()));
            List<String> list = new ArrayList<>(set);
            userRelationForm.setUserIds(list);
            userRelationService.saveObjectId(objectId, userRelationForm);
        }
        userService.delCurUser(userRelationForm.getUserIds());
        return ActionResult.success(MsgCode.SU002.get());
    }

    /**
     * 添加区域限制
     */
    @RequestMapping("/create")
    @PostMapping
    public ActionResult create(@RequestBody UserRelationPagination userRelationPagination) {
        UserInfo userInfo = userProvider.get();
        String collect = "";
        if (ObjectUtil.isNotNull(userRelationPagination.getAddress())) {
            String[] addressStr = userRelationPagination.getAddress().toArray(new String[]{});
            List<String> list1 = new ArrayList<>();
            for (String s : addressStr) {
                list1.add(s);
            }
            collect = list1.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
            collect = "[" + collect + "]";
        }
        if (ObjectUtil.isNotNull(userRelationPagination.getUserId())) {
            for (String s : userRelationPagination.getUserId()) {
                //先判断当前要加数据是否已有数据。
                QueryWrapper<UserRelationEntity> userRelationEntityQueryWrapper = new QueryWrapper<>();
                userRelationEntityQueryWrapper.lambda().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, s).eq(UserRelationEntity::getObjectId, collect.replaceAll(" ", ""));
                UserRelationEntity one = userRelationService.getOne(userRelationEntityQueryWrapper);
                if (ObjectUtil.isNotNull(one)) {
                    continue;
                }

                UserRelationEntity userRelationEntity = new UserRelationEntity();
                String mainId = RandomUtil.uuId();
                userRelationEntity.setUserId(s);
                userRelationEntity.setId(mainId);
                userRelationEntity.setObjectType("Area");
                userRelationEntity.setObjectId(collect.replaceAll(" ", ""));
                userRelationEntity.setCreatorUserId(userInfo.getUserId());
                userRelationEntity.setCreatorTime(DateUtil.getNowDate());
                userRelationService.save(userRelationEntity);
            }
        }
        return ActionResult.success();
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping("/delete")
    @DSTransactional
    public ActionResult delete(@RequestBody UserRelationPagination userRelationPagination) {
        String str = userRelationPagination.getUserId().get(0);
        QueryWrapper<UserRelationEntity> userRelationEntityQueryWrapper = new QueryWrapper<>();
        List<String> ids = new ArrayList<>();
        //如果当前地址为空，说明要取消所有授权
        if (ObjectUtil.isNotNull(userRelationPagination.getAddress())) {
            userRelationEntityQueryWrapper.lambda().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, str);
            List<UserRelationEntity> list = userRelationService.list(userRelationEntityQueryWrapper);
            List<String> collect = list.stream().map(UserRelationEntity::getId).collect(Collectors.toList());
            userRelationService.delete(collect.toArray(new String[]{}));
            return ActionResult.success();
        }

        String[] addressStr = userRelationPagination.getAddress().toArray(new String[]{});
        List<String> list1 = new ArrayList<>();
        for (String ss : addressStr) {
            list1.add(ss);
        }
        String collect = list1.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(", "));
        collect = "[" + collect + "]";
        userRelationEntityQueryWrapper.lambda().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, str).eq(UserRelationEntity::getObjectId, collect.replaceAll(" ", "")).or();
        UserRelationEntity user = userRelationService.getOne(userRelationEntityQueryWrapper);
        if (ObjectUtil.isNotNull(user)) {
            String strTemp = list1.get(0);
            strTemp = "[\"" + strTemp + "\"]";
            UserRelationEntity relationServiceOne = userRelationService.getOne(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, str).eq(UserRelationEntity::getObjectId, strTemp.replaceAll(" ", "")));
            ids.add(relationServiceOne.getId());
            userRelationService.delete(ids.toArray(new String[]{}));
            return ActionResult.success();
        }
        ids.add(user.getId());
        userRelationService.delete(ids.toArray(new String[]{}));
        return ActionResult.success();
    }
}
